package org.btik.bean.impl.temporary;

import org.btik.context.exception.LightContextException;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.function.BiConsumer;

/**
 * bean缓存结构
 */
public class CacheStruct<T> {
    private final HashMap<String, T> idBeanMap = new HashMap<>();

    private final LinkedList<T> noneIdBeans = new LinkedList<>();


    public HashMap<String, T> getIdBeanMap() {
        return idBeanMap;
    }

    public LinkedList<T> getNoneIdBeans() {
        return noneIdBeans;
    }

    public void save(String beanId, T value) {
        if (beanId == null || beanId.isEmpty()) {
            noneIdBeans.add(value);
            return;
        }

        idBeanMap.compute(beanId, (k, oldValue) -> {
            if (oldValue != null) {
                throw new LightContextException("Unique bean id already exists :" + beanId);
            }
            return value;
        });
    }

    /**
     * 解析，并移出缓存
     */
    public void resolve(BiConsumer<String, T> resolveConsumer) {
        T o;
        while ((o = noneIdBeans.poll()) != null) {
            // 无id时传入null 当解析的属性小于属性数量时，重新添加
            resolveConsumer.accept(null, o);
        }
        idBeanMap.forEach(resolveConsumer);
        idBeanMap.clear();

    }

}
